package com.anc.platform.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: Anc
 * @date: 2021/4/12 10:49
 * @description: 线程池配置
 */
@Configuration
public class ThreadPoolConfig {

    @Bean("asyncTaskExecutor")
    public ThreadPoolTaskExecutor purchaseThreadPool() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        // 核心线程池数
        pool.setCorePoolSize(8);
        // 最大线程
        pool.setMaxPoolSize(16);
        // 队列容量
        pool.setQueueCapacity(1024);
        // 线程名前缀
        pool.setThreadNamePrefix("task-");
        // 允许的空闲时间，当线程空闲时间达到keepAliveTime时，线程会退出，直到线程数量=corePoolSize
        pool.setKeepAliveSeconds(600);
        pool.setWaitForTasksToCompleteOnShutdown(true);
        pool.setAwaitTerminationSeconds(60);
        // 队列满，不在新线程中执行任务，而是有调用者所在的线程来执行
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        pool.initialize();
        return pool;
    }

    /**
     * 定时线程池
     *
     * @return
     */
    @Bean
    public ScheduledThreadPoolExecutor purchaseScheduledThreadPool() {
        ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(1);
        return pool;
    }
}
